package com.cote.douhahou.pretloan.status;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.cote.douhahou.pretloan.service.CusServiceAkomapalendDialog;
import com.cote.douhahou.pretloan.beans.AppAkomapalendConfigCustomize;
import com.cote.douhahou.pretloan.beans.LoanApDAkomapalendetailInfo;
import com.cote.douhahou.pretloan.beans.ProcessInAkomapalendfo;
import com.cote.douhahou.pretloan.beans.RecommendAkomapalendAppInfo;
import com.cote.douhahou.pretloan.home.HomeActivity;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LnStatAkomapalendeFailFragment extends BaseAkomapalendLnFragment {

    private TextView loanAmountTv,loanTermTv;
    private TextView tipsTv;
    private View recommendView;
    private LinearLayout recommendGroupLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fail, container, false);

        loanAmountTv = view.findViewById(R.id.flsfa_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.flsfa_tv_loan_term);
        tipsTv = view.findViewById(R.id.flsfa_tv_tips);
        recommendView = view.findViewById(R.id.flsfa_view_recommend);
        recommendGroupLayout = view.findViewById(R.id.flsfa_layout_recommend_group);

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.flsfa_refreshlayout);

        view.findViewById(R.id.flsfa_ib_customer_service).setOnClickListener(v -> new CusServiceAkomapalendDialog(getContext()).show());

        refreshLayout.setOnRefreshListener(() -> {
            HttpHelper.inst().submitEvent("REJECT","REFRESH_CLICK","");
            HttpHelper.inst().process(requireActivity(),
                () -> {
                    String state = ProcessInAkomapalendfo.instance().getAkomapaLendUtil();
                    if (AkomapaLendUtil.stateIsChange(state)) {//刷新用户状态
                        FragmentActivity activity = requireActivity();
                        AkomapaLendUtil.clearState();
                        activity.startActivity(new Intent(activity, HomeActivity.class));
                        activity.finish();
                    }else HttpHelper.inst().fetchAppConfig(requireActivity(),this::refreshRecommendAppList_akomapalend);
                }
            );
            refreshLayout.setRefreshing(false);
        });

        HttpHelper.inst().applyDetails(requireActivity(), this::refreshLoanDetail);

        return view;
    }


    @SuppressLint("SetTextI18n")
    public void refreshLoanDetail(){

        String currency = LoanApDAkomapalendetailInfo.instance().getCurrency_akomapalend();

        loanAmountTv.setText(LoanApDAkomapalendetailInfo.instance().getAmount_akomapalend()+" "+currency);
        loanTermTv.setText(LoanApDAkomapalendetailInfo.instance().getTermStr_akomapalend(requireContext()));

        //提示文案显示
        tipsTv.setText(getString(R.string.loan_fail_tips, LoanApDAkomapalendetailInfo.instance().getReApplyDate()));

        //app推荐显示
        refreshRecommendAppList_akomapalend();

    }


    public void refreshRecommendAppList_akomapalend(){
        if (!AppAkomapalendConfigCustomize.instance().getRecommendFlag_akomapalend()) return;
        recommendGroupLayout.removeAllViews();
        ArrayList<RecommendAkomapalendAppInfo> recommendAppInfos = AppAkomapalendConfigCustomize.instance().getRecommendAppList_akomapalend();
        for (RecommendAkomapalendAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp_akomapalend(recommendAppInfo);
        }
    }

    //添加推荐App
    private void addRecommendApp_akomapalend(RecommendAkomapalendAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend,null);

        ImageView appLogoIv = itemView.findViewById(R.id.iraa_iv_app_logo);
        TextView appNameTv = itemView.findViewById(R.id.iraa_tv_app_name);
        TextView appAmountTv = itemView.findViewById(R.id.iraa_tv_app_amount);
        TextView appRateTv = itemView.findViewById(R.id.iraa_tv_app_rate);
        TextView appDownloadTv = itemView.findViewById(R.id.iraa_tv_app_download);
        View installBtn = itemView.findViewById(R.id.iraa_btn_install);

        appNameTv.setText(recommendAppInfo.getAp_akomapalendpName());
        appAmountTv.setText(recommendAppInfo.getAmou_akomapalendntText());
        appRateTv.setText(recommendAppInfo.getSc_akomapalendore());
        appDownloadTv.setText(recommendAppInfo.getDow_akomapalendnloads());

        //Install按键
        installBtn.setOnClickListener(v -> {
            HttpHelper.inst().submitEvent("REJECT","RECOMMEND_"+recommendAppInfo.getAp_akomapalendpName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getP_akomapalendath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });
        //加载logo
        if (recommendAppInfo.getLogo_akomapalendBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getL_akomapalendogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLo_akomapalendgoB_akomapalenditmap(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> appLogoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else appLogoIv.setImageBitmap(recommendAppInfo.getLogo_akomapalendBitmap());

        recommendGroupLayout.addView(itemView);
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpHelper.inst().submitEvent("REJECT","START","");
    }

    @Override
    public void onPause() {
        super.onPause();
        HttpHelper.inst().submitEvent("REJECT","END","");
    }

}